package com.android.manghe.user.activity

import android.app.Activity
import android.app.Service
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.telephony.TelephonyManager
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.text.method.HideReturnsTransformationMethod
import android.text.method.PasswordTransformationMethod
import android.view.View
import com.android.base.frame.title.ETitleType
import com.android.base.frame.view.MVPActivity
import com.android.base.tools.ToastUtil
import com.android.base.tools.permission.OnPermissionResultListener
import com.android.base.tools.permission.PermissionUtil
import com.android.manghe.R
import com.android.manghe.cache.UserHolder
import com.android.manghe.config.events.ShowLuckDrawDialog
import com.android.manghe.user.presenter.PLogin
import com.eightbitlab.rxbus.Bus
import com.umeng.socialize.UMAuthListener
import com.umeng.socialize.UMShareAPI
import com.umeng.socialize.bean.SHARE_MEDIA
import com.yanzhenjie.permission.runtime.Permission
import kotlinx.android.synthetic.main.activity_login.*

class LoginActivity : MVPActivity<PLogin>() {

    private var mIsPswVisible = false
    private var mShareAPI: UMShareAPI? = null

    companion object {
        fun showActivity(context: Context) {
            val intent = Intent(context, LoginActivity::class.java)
            context.startActivity(intent)
        }
        fun showNewTaskActivity(context: Context) {
            val intent = Intent(context, LoginActivity::class.java)
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            context.startActivity(intent)
        }
        fun showActivity(context: Context, giftAmount: String?) {
            val intent = Intent(context, LoginActivity::class.java)
            giftAmount?.let {
                intent.putExtra("giftAmount", it)
            }
            context.startActivity(intent)
        }
    }


    override fun getLayoutId() = R.layout.activity_login
    override fun showToolBarType(): ETitleType {
        return ETitleType.SIMPLE_TITLE
    }

    override fun initData(savedInstanceState: Bundle?) {
        p.giftAmount = intent.getStringExtra("giftAmount")
        titleBar.setToolbar("登录").setLeftIcon(R.mipmap.icon_back_black).hideBottomLine().setTitleAndStatusBgColor(R.color.white)
        UserHolder.clearInfo(this)
        mShareAPI = UMShareAPI.get(this)
        initListener()
    }

    private fun initListener() {
        layoutReg.setOnClickListener {
            RegActivity.showActivity(this@LoginActivity, p.giftAmount, 2000)
        }
        tvForgetPsw.setOnClickListener {
            ResetPswActivity.showActivity(this@LoginActivity)
        }
        ivEye.setOnClickListener {
            changePswVisible()
        }
        btnLogin.setOnClickListener {
            val tel = etTel.text.toString().trim()
            val psw = etPsw.text.toString().trim()
            if (TextUtils.isEmpty(tel)) {
                ToastUtil.showShort(this@LoginActivity, "请输入手机号码")
                return@setOnClickListener
            }
            if (TextUtils.isEmpty(psw)) {
                ToastUtil.showShort(this@LoginActivity, "请输入密码")
                return@setOnClickListener
            }
            showLoadingDialog()
            p.login(tel, psw, false)
        }

        etTel.addTextChangedListener(object: TextWatcher{
            override fun afterTextChanged(s: Editable?) {
            }

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                ivX.visibility = if(etTel.text.toString().isNotEmpty()) View.VISIBLE else View.GONE
            }

        })

        ivX.setOnClickListener {
            etTel.setText("")
        }


        ivWechat.setOnClickListener {
            mShareAPI?.getPlatformInfo(this, SHARE_MEDIA.WEIXIN, object : UMAuthListener {
                /**
                 * @desc 授权成功的回调
                 * @param platform 平台名称
                 * @param action 行为序号，开发者用不上
                 * @param data 用户资料返回
                 */
                override fun onComplete(platform: SHARE_MEDIA?, action: Int, data: MutableMap<String, String>?) {
                    if(data != null) {
                        showLoadingDialog()
                        p.otherLoginToService(2, data["openid"], data["unionid"], data["name"], data["iconurl"])
                    }else{
                        ToastUtil.showShort(this@LoginActivity, "登录失败")
                    }
                }

                /**
                 * @desc 授权取消的回调
                 * @param platform 平台名称
                 * @param action 行为序号，开发者用不上
                 */
                override fun onCancel(platform: SHARE_MEDIA?, action: Int) {
                    ToastUtil.showShort(this@LoginActivity, "取消登录")
                }

                /**
                 * @desc 授权失败的回调
                 * @param platform 平台名称
                 * @param action 行为序号，开发者用不上
                 * @param t 错误原因
                 */
                override fun onError(platform: SHARE_MEDIA?, action: Int, t: Throwable?) {
                    ToastUtil.showShort(this@LoginActivity, ""+ t!!.message)
                }

                /**
                 * @desc 授权开始的回调
                 * @param platform 平台名称
                 */
                override fun onStart(platform: SHARE_MEDIA?) {
                }

            })
        }
        ivQQ.setOnClickListener {
            PermissionUtil.requestPermissions(this, {
                mShareAPI?.getPlatformInfo(this@LoginActivity, SHARE_MEDIA.QQ, object : UMAuthListener {
                    /**
                     * @desc 授权成功的回调
                     * @param platform 平台名称
                     * @param action 行为序号，开发者用不上
                     * @param data 用户资料返回
                     */
                    /**
                     * @desc 授权成功的回调
                     * @param platform 平台名称
                     * @param action 行为序号，开发者用不上
                     * @param data 用户资料返回
                     */
                    override fun onComplete(platform: SHARE_MEDIA?, action: Int, data: MutableMap<String, String>?) {
                        runOnUiThread {
                            if (data != null) {
                                showLoadingDialog()
                                p.otherLoginToService(
                                    3,
                                    data["openid"],
                                    data["unionid"],
                                    data["name"],
                                    data["iconurl"]
                                )
                            } else {
                                ToastUtil.showShort(this@LoginActivity, "登录失败")
                            }
                        }
                    }

                    /**
                     * @desc 授权取消的回调
                     * @param platform 平台名称
                     * @param action 行为序号，开发者用不上
                     */
                    /**
                     * @desc 授权取消的回调
                     * @param platform 平台名称
                     * @param action 行为序号，开发者用不上
                     */
                    override fun onCancel(platform: SHARE_MEDIA?, action: Int) {
                        runOnUiThread {
                            ToastUtil.showShort(this@LoginActivity, "取消登录")
                        }
                    }

                    /**
                     * @desc 授权失败的回调
                     * @param platform 平台名称
                     * @param action 行为序号，开发者用不上
                     * @param t 错误原因
                     */
                    /**
                     * @desc 授权失败的回调
                     * @param platform 平台名称
                     * @param action 行为序号，开发者用不上
                     * @param t 错误原因
                     */
                    override fun onError(platform: SHARE_MEDIA?, action: Int, t: Throwable?) {
                        t?.printStackTrace()
                        runOnUiThread {
                            ToastUtil.showShort(this@LoginActivity, "登录失败")
                        }
                    }

                    /**
                     * @desc 授权开始的回调
                     * @param platform 平台名称
                     */
                    /**
                     * @desc 授权开始的回调
                     * @param platform 平台名称
                     */
                    override fun onStart(platform: SHARE_MEDIA?) {
                    }

                })
            }, Permission.WRITE_EXTERNAL_STORAGE)
        }
    }

    private fun changePswVisible() {
        etPsw.transformationMethod =
            if (mIsPswVisible) PasswordTransformationMethod.getInstance() else HideReturnsTransformationMethod.getInstance()
        mIsPswVisible = !mIsPswVisible
        ivEye.setImageResource(if (mIsPswVisible) R.mipmap.visible else R.mipmap.invisible)
    }

    //是否跳转到首页转盘
    fun loginOk(isFirstLogin: Boolean) {
        val tm = getSystemService(Service.TELEPHONY_SERVICE) as TelephonyManager
//        TuiAManager.send(this, MD5.md5(tm.getDeviceId()), 3)
        ToastUtil.showShort(this, "登录成功")
        finish()
        if(isFirstLogin && TextUtils.isEmpty(p.giftAmount)){
            //跳转到登录首页转盘 -> 首次登录+不是转盘抽奖后进来的
            Bus.send(ShowLuckDrawDialog())
        }
    }

    fun loginFail(text: String?) {
        ToastUtil.showShort(this, if (TextUtils.isEmpty(text)) "登录失败" else text)
    }

    fun closeLoadingDialog() {
        hideLoadingDialog()
    }

    fun toBindTel(avatar :String, openid : String, type:String, nick:String){
        ToastUtil.showShort(this, "请绑定手机号码")
        //打开注册页面
        RegActivity.showActivity(this, avatar, openid,type, nick,  1000)
    }
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data)
        if(resultCode == Activity.RESULT_OK){
            if(requestCode == 1000){
                val bindType = data?.getStringExtra("bindType")
                if(!bindType.isNullOrEmpty()) {
                    showLoadingDialog()
                    p.login(data.getStringExtra("tel"), data.getStringExtra("psw"), true)
//                    when (bindType) {
//                        "wx" -> ivWechat.performClick()
//                        "qq" -> ivQQ.performClick()
//                    }
                }
            }else if(requestCode == 2000){
                //注册成功，自动登录
                showLoadingDialog("登录中")
                p.login(data?.getStringExtra("tel"), data?.getStringExtra("psw"), true)
            }
        }
    }
    override fun onDestroy() {
        super.onDestroy()
        UMShareAPI.get(this).release()
    }
}